<?php
// +----------------------------------------------------------------------
// | 应用公共文件
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------


use app\api\model\BaseConfig as BaseConfigModel;
use think\facade\Db;
use think\facade\Log; 
use think\facade\Config;
use think\Response;

error_reporting(0);


/**
 * 随机字符
 * @param int $length 长度
 * @param string $type 类型
 * @param int $convert 转换大小写 1大写 0小写
 * @return string
 */
function random($length=10, $type='letter', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'letter';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string[mt_rand(0, $strlen)];
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}


//后台sql输入框语句过滤
function sql_replace($str){
	$farr = ["/insert[\s]+|update[\s]+|create[\s]+|alter[\s]+|delete[\s]+|drop[\s]+|load_file|outfile|dump/is"];
	$str = preg_replace($farr,'',$str);
	return $str;
}


//上传文件黑名单过滤
function upload_replace($str){
	$farr = ["/php|php3|php4|php5|phtml|pht|/is"];
	$str = preg_replace($farr,'',$str);
	return $str;
}


//查询方法过滤
function serach_in($str){
	$farr = ["/^select[\s]+|insert[\s]+|and[\s]+|or[\s]+|create[\s]+|update[\s]+|delete[\s]+|alter[\s]+|count[\s]+|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i"];
	$str = preg_replace($farr,'',$str);
	return trim($str);
}


//获取键值对信息
function getItemData($data){
	$str = in_array(json_encode(array_values($data)),['[]','[[]]']) ? '' : json_encode(array_values($data),JSON_UNESCAPED_UNICODE);
	return $str;
}


/**
 * tp官方数组查询方法废弃，数组转化为现有支持的查询方法
 * @param array $data 原始查询条件
 * @return array
 */
function formatWhere($data){
	$where = [];
	foreach( $data as $k=>$v){
		if(is_array($v)){
			if(((string) $v[1] <> null && !is_array($v[1])) || (is_array($v[1]) && (string) $v[1][0] <> null)){
				switch(strtolower($v[0])){			
					//模糊查询
					case 'like':
						$v[1] = '%'.$v[1].'%';
					break;
					
					case 'regex':
						$v[0] = 'like';
					break;
					
					//表达式查询
					case 'exp':
						$v[1] = Db::raw($v[1]);
					break;
				}
				$where[] = [$k,$v[0],$v[1]];
			}
		}else{
			if((string) $v != null){
				$where[] = [$k,'=',$v];
			}
		}
	}
	return $where;
}



/*获取应用url前缀*/
function getBaseUrl(){
	$baseAppName = app('http')->getName();
	if(config('app.app_map')){
		$newapp = array_flip(config('app.app_map'))[$baseAppName];
		if($newapp) $baseAppName = $newapp;
	}

	$basename ='/'.$baseAppName;

	if(config('app.domain_bind')){
		$newapp = array_flip(config('app.domain_bind'))[$baseAppName];
		if($newapp) $basename = '';
	}
	
	return $basename;
}


/**
 * 实例化数据库类
 * @param string        $name 操作的数据表名称（不含前缀）
 * @param array|string  $config 数据库配置参数
 * @param bool          $force 是否强制重新连接
 * @return \think\db\Query
 */
if (!function_exists('db')) {
	
    function db($name = '',$connect='')
    {
		if(empty($connect)){
			$connect = config('database.default');
		}
        return Db::connect($connect,false)->name($name);
    }
}

//计算USDT手续费
function commission($num,$price)
{

    $sell_money = BaseConfigModel::config_data('sell_money');

    //计算USDT价格
    $usdt_price = bcmul($num,$price,4);

    //计算交易手续费
    $sell_num = bcmul($usdt_price,bcdiv($sell_money,100,4),4);

    //计算获得的USDT;
    return bcsub($usdt_price,$sell_num,4);
}

//计算手续费
function transaction_commission($num,$price)
{
    $sell_money = BaseConfigModel::config_data('sell_money');

    //计算USDT价格
    $usdt_price = bcmul($num,$price,4);

    //计算交易手续费
    return bcmul($usdt_price,bcdiv($sell_money,100,4),4);
}

if(!function_exists('api_success')){
    /**
     * API 成功返回
     * @param $info 主要参数内容
     * @param string $msg   备注
     * @param string $language  语言
     * @param array $header head
     * @param array $options    get
     * @return Response
     */
    function api_success($info = [],$msg='',$language='traditional'){
        header('Content-Type: application/json');
        $data = [
            'code'    =>  200,
            'msg'   =>  !empty($msg) ? config('language')[$msg][$language] : '',
            'data'  =>  $info
        ];
        die(json_encode($data));

    }
}

if(!function_exists('api_error')){
    /**
     * API 失败返回
     * @param $info 失败参数
     * @param string $msg   失败提示
     * @param string $language  语言
     * @param array $header head
     * @param array $options    get
     * @return Response
     */
    function api_error($info = [],$msg='',$language='traditional',$code = 0){
        header('Content-Type: application/json');
        $data = [
            'code'    =>  $code,
            'msg'   =>  !empty($msg) ? config('language')[$msg][$language] : '',
            'data'  =>  $info
        ];
        die(json_encode($data,true));
    }
}

if(!function_exists('file_language')){
    function file_language($name,$language = 'traditional'){
        $file = $name; //.'as l_'.$name;
        if($language == 'traditional') $file = 't_'.$name.' as '.$name;
        if($language == 'english') $file = 'e_'.$name.' as '.$name;
        return $file;
    }
}

if(!function_exists('id_language')){
    function id_language($name,$language = 'traditional'){
        $file = 1;
        if($language == 'traditional') $file = 2;
        if($language == 'english') $file = 3;
        return $file;
    }
}

/**
 * 验证是否是以太坊钱包地址(BEP/以太)
 */
if(!function_exists('isValidEthereumAddress')){
    function isValidEthereumAddress($address) {
        // 验证地址是否以"0x"开头
        if (!preg_match('/^0x[a-fA-F0-9]{40}$/', $address)) return false;
        // 验证地址长度
        if (strlen($address) !== 42) return false;

        return true;
    }
}

/**
 * 验证是否是波场钱包地址(TRC20)
 */
if(!function_exists('isValidTronAddress')){
    function isValidTronAddress($address) {
        // 验证地址是否以"T"开头，后面跟随33个字符的Base58编码
        if (!preg_match('/^T[1-9A-HJ-NP-Za-km-z]{33}$/', $address)) return false;
        // 验证地址长度
        if (strlen($address) !== 34) return false;

        return true;
    }
}

/**
 * 获取用户TRC20钱包地址
 * @param $mid  用户ID
 * @return mixed|string
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function trc_address($mid){

    $time = time();
    //生成私钥
    $sign = trc_sign(['mid'=>$mid],env('SECRET_KEY'),$time);
    //请求数据
    $options = [
        'form_params'   =>  ['mid'=>$mid],
    ];
    $headers = [
        'headers' => [
            'accept'=>'application/json',
            'content-type'=>'application/json',
            'TRC-PUBLIC-KEY'=>env('TRC_PUBLIC_KEY'),
            'TRC-SIGN'=>$sign,
            'TRC-SEND-TIME'=>$time,
        ]
    ];
    $client = new Client($headers);
    $response = $client->request('POST', 'https://trx.xinhuoio.com/index/address', $options);
    $response_data = $response->getBody();
    return json_decode($response_data,true);
}

/**
 * 获取用户TRC20钱包地址
 * @param $mid  用户ID
 * @return mixed|string
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function bep_address($mid){

    $time = time();
    //生成私钥
    $sign = trc_sign(['mid'=>$mid],env('SECRET_KEY'),$time);
    //请求数据
    $options = [
        'form_params'   =>  ['mid'=>$mid],
    ];
    $headers = [
        'headers' => [
            'accept'=>'application/json',
            'content-type'=>'application/json',
            'TRC-PUBLIC-KEY'=>env('TRC_PUBLIC_KEY'),
            'TRC-SIGN'=>$sign,
            'TRC-SEND-TIME'=>$time,
        ]
    ];
    $client = new Client($headers);
    $response = $client->request('POST', 'https://trx.xinhuoio.com/index/BEP_address', $options);
    $response_data = $response->getBody();
    return json_decode($response_data,true);
}

/**
 * 接口生成签名
 * @param $sign_arr 内容
 * @param $secret_key   私钥
 * @param $time 时间
 * @return false|string
 */
function trc_sign($sign_arr,$secret_key,$time){
    $sign_arr['secret_key'] =   $secret_key;
    $sign_arr['time'] =   $time;

    // 对数组进行排序
    uksort($sign_arr, function ($a, $b) use ($sign_arr) {
        $lengthA = strlen($a);
        $lengthB = strlen($b);
        $minLength = min($lengthA, $lengthB);
        for ($i = 0; $i < $minLength; $i++) {
            $charA = $a[$i];
            $charB = $b[$i];
            if ($charA !== $charB) {
                return ord($charA) - ord($charB);
            }
        }
        return $lengthA - $lengthB;
    });

    $sign = '';
    foreach ($sign_arr as $k => $v){
        if($k != 'sign' && !empty($v)){
            if(is_array($v)) $v = json_encode($v,true);
            if(!empty($sign)) $sign .= '&';
            $sign .= $k.'='.$v;
        }
    }

    return hash('sha256',md5($sign));
}
